package com.lmk.mkcc.mq.consumer;

import com.alibaba.fastjson.JSONObject;
import com.lmk.mkcc.domain.MessageSms;
import com.lmk.mkcc.dto.CourseSendMessageDto;
import com.lmk.mkcc.dto.UserSmsDto;
import com.lmk.mkcc.service.IMessageSmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;


@Component
@Slf4j
@RocketMQMessageListener(
        consumerGroup = "send-message-group",
        topic = "topic-send-message",
        selectorExpression = "tag-send-message",
        messageModel = MessageModel.CLUSTERING
)
public class SendMessageConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private IMessageSmsService smsService;
    @Override
    public void onMessage(MessageExt messageExt) {
        // 获取消息体
        byte[] body = messageExt.getBody();
        // 判断body是否为null
        if (body==null || body.length==0){
            return;
        }
        // 将消息体进行转化
        CourseSendMessageDto courseSendMessageDto = JSONObject.parseObject(new String(body, StandardCharsets.UTF_8), CourseSendMessageDto.class);

        // 将信息保存到消息数据库
        savemessage(courseSendMessageDto);
        // 消息发送消息成功
        log.info("消息发送成功");
    }

    private void savemessage(CourseSendMessageDto courseSendMessageDto) {
        String title = courseSendMessageDto.getTitle();
        String content = courseSendMessageDto.getContent();
        List<UserSmsDto> users = courseSendMessageDto.getUserSmsDtos();
        MessageSms messageSms = new MessageSms();
        messageSms.setTitle(title);
        messageSms.setContent(content);
        messageSms.setSendTime(new Date());
        for (UserSmsDto user : users) {
            messageSms.setUserId(user.getId());
            messageSms.setIp("127.0.0.1");
            smsService.insert(messageSms);
        }

    }
}
